<!DOCTYPE html>
<html>
  <head>
    <title>chat</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
  	<div id="h2arr"><h2 id="h2a"></h2></div>
    <textarea id="tec"></textarea>
    <button id="btn" onclick="btnclick()">提交</button>
	<button id="btn" onclick="btndeleteclick()">清空聊天记录</button>
    <script type="text/javascript">
    	var Ajax={
		    get: function(url, fn) {
		        var xhr = new XMLHttpRequest();  // XMLHttpRequest对象用于在后台与服务器交换数据          
		        xhr.open('GET', url, true);
		        xhr.onreadystatechange = function() {
		            if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) { // readyState == 4说明请求已完成
		                fn.call(this, xhr.responseText);  //从服务器获得数据
		            }
		        };
		        xhr.send();
		    },
		    post: function (url, data, fn) {         // datat应为'a=a1&b=b1'这种字符串格式，在jq里如果data为对象会自动将对象转成这种字符串格式
		        var xhr = new XMLHttpRequest();
		        xhr.open("POST", url, true);
		        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  // 添加http头，发送信息至服务器时内容编码类型
		        xhr.onreadystatechange = function() {
		            if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {  // 304未修改
		                fn.call(this, xhr.responseText);
		            }
		        };
		        xhr.send(data);
		    }
		}

		var theResponse = window.prompt("欢迎","请在此输入您的姓名!")

		setInterval(function(){
			Ajax.get(document.location.origin+'/chat',function(data,result){
				document.getElementById('h2arr').innerHTML = '';
				var textdata = eval(data);
				var ia = document.getElementById('h2arr');
				for(i in textdata){
					var h2 = document.createElement('h2');
					h2.id = 'h2a';
					h2.innerHTML = textdata[i];
					ia.appendChild(h2);
				}
			})
		},1000)
		

	function btnclick(){
		var rere = document.getElementById('tec').value;

		if(rere&&theResponse){
			Ajax.get(document.location.origin+'/chat?chat='+theResponse+':'+rere,function(data,result){
				document.getElementById('h2arr').innerHTML = '';
				var textdata = eval(data);
				var ia = document.getElementById('h2arr');
				for(i in textdata){
					var h2 = document.createElement('h2');
					h2.id = 'h2a';
					h2.innerHTML = textdata[i];
					ia.appendChild(h2);
				}
			})
		}else{
			alert('请先输入');
		}
		
	}

	function btndeleteclick(){
		var password = prompt('请输入口令');
		Ajax.get(document.location.origin+'/chat/delete?password='+password,function(data,result){
			alert(data);
		})
	}
		
    </script>
  </body>
</html>
